'use strict';

const Controller = require('egg').Controller;
const Response = require('../utils/response');

class ArticleController extends Controller {
  // 创建文章
  async create() {
    const { ctx } = this;
    const { title, summary, content, coverImage, status } = ctx.request.body;
    const userId = ctx.state.user.id; // 假设从token中获取用户ID

    try {
      const article = await ctx.service.article.create({
        title,
        summary,
        content,
        cover_image: coverImage,
        user_id: userId,
        status,
      });
      ctx.body = Response.success(article.id, '创建成功');
    } catch (error) {
      ctx.body = Response.error(500, '创建失败', error.message);
    }
  }

  // 删除文章
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    const userId = ctx.state.user.id;

    try {
      const result = await ctx.service.article.destroy(id, userId);
      if (result) {
        ctx.body = Response.success(null, '删除成功');
      } else {
        ctx.body = Response.error(403, '无权删除该文章');
      }
    } catch (error) {
      ctx.body = Response.error(500, '删除失败', error.message);
    }
  }

  // 更新文章
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { title, summary, content, cover_image, status } = ctx.request.body;
    const userId = ctx.state.user.id;

    try {
      const result = await ctx.service.article.update(id, {
        title,
        summary,
        content,
        cover_image,
        status,
      }, userId);
      if (result) {
        ctx.body = Response.success(result, '更新成功');
      } else {
        ctx.body = Response.error(403, '无权更新该文章');
      }
    } catch (error) {
      ctx.body = Response.error(500, '更新失败', error.message);
    }
  }

  // 获取单个文章
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      const article = await ctx.service.article.findById(id);
      if (article) {
        ctx.body = Response.success(article, '获取成功');
      } else {
        ctx.body = Response.error(404, '文章不存在');
      }
    } catch (error) {
      ctx.body = Response.error(500, '获取失败', error.message);
    }
  }

  // 获取文章列表
  async index() {
    const { ctx } = this;
    const { page = 1, pageSize = 10, status, title } = ctx.query;

    try {
      const result = await ctx.service.article.findList({
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        status: status ? parseInt(status) : undefined,
        title,
      });
      ctx.body = Response.success(result, '获取成功');
    } catch (error) {
      ctx.body = Response.error(500, '获取失败', error.message);
    }
  }
}

module.exports = ArticleController;